using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TangLiveRecorder.Models;
using TangLiveRecorder.Services;

namespace TangLiveRecorder
{
    public partial class Data
    {
        private static bool _livesInitialized = false;

        public static List<LiveInfo> lives = new List<LiveInfo>
        {
            new LiveInfo
            {
                Guid = Guid.NewGuid().ToString(),
                Avatar = "https://i0.hdslb.com/bfs/face/default.jpg",
                Name = "游戏主播小明",
                Description = "专业游戏解说，每晚8点准时开播",
                Url = "https://live.bilibili.com/123456",
                Status = true
            },
            new LiveInfo
            {
                Guid = Guid.NewGuid().ToString(),
                Avatar = "https://i0.hdslb.com/bfs/face/default.jpg",
                Name = "音乐达人小红",
                Description = "分享好听的音乐，治愈你的心灵",
                Url = "https://live.bilibili.com/789012",
                Status = false
            },
            new LiveInfo
            {
                Guid = Guid.NewGuid().ToString(),
                Avatar = "https://i0.hdslb.com/bfs/face/default.jpg",
                Name = "技术分享者",
                Description = "编程技术分享，代码实战演示",
                Url = "https://www.douyu.com/123456",
                Status = true
            },
            new LiveInfo
            {
                Guid = Guid.NewGuid().ToString(),
                Avatar = "https://i0.hdslb.com/bfs/face/default.jpg",
                Name = "美食博主",
                Description = "教你做各种美味佳肴",
                Url = "https://www.huya.com/789012",
                Status = false
            },
            new LiveInfo
            {
                Guid = Guid.NewGuid().ToString(),
                Avatar = "https://i0.hdslb.com/bfs/face/default.jpg",
                Name = "户外探险家",
                Description = "带你看遍世界美景",
                Url = "https://live.douyin.com/345678",
                Status = true
            }
        };

        // 直播相关事件
        public static event EventHandler<LiveEventArgs> LiveAdded;

        public static event EventHandler<LiveEventArgs> LiveRemoved;

        public static event EventHandler<LiveEventArgs> LiveUpdated;

        public static event EventHandler LivesCleared;

        /// <summary>
        /// 初始化直播数据持久化服务
        /// </summary>
        /// <param name="persistenceService">持久化服务实例</param>
        public static void InitializeLivePersistence(DataPersistenceService persistenceService)
        {
            if (_livesInitialized) return;

            // 加载已保存的数据
            var savedLives = persistenceService.LoadLives();
            if (savedLives.Count > 0)
            {
                lives.Clear();
                foreach (var live in savedLives)
                {
                    live.IsRecording = false;
                }
                lives.AddRange(savedLives);
                AddLog($"从持久化存储加载了 {savedLives.Count} 个直播记录");
            }

            _livesInitialized = true;
        }

        /// <summary>
        /// 保存直播数据到持久化存储
        /// </summary>
        private static void SaveLivesToPersistence()
        {
            if (_persistenceService != null && _livesInitialized)
            {
                Task.Run(() => _persistenceService.SaveLivesAsync(new List<LiveInfo>(lives)));
            }
        }

        /// <summary>
        /// 添加直播
        /// </summary>
        /// <param name="liveInfo">直播信息</param>
        public static void AddLive(LiveInfo liveInfo)
        {
            if (liveInfo == null) return;

            // 检查是否已存在相同URL的直播
            if (!lives.Any(l => l.Url.Equals(liveInfo.Url, StringComparison.OrdinalIgnoreCase)))
            {
                if (string.IsNullOrEmpty(liveInfo.Guid))
                {
                    liveInfo.Guid = Guid.NewGuid().ToString();
                }

                lives.Add(liveInfo);
                LiveAdded?.Invoke(null, new LiveEventArgs(liveInfo));
                AddLog($"添加直播: {liveInfo.Name} - {liveInfo.Url}");
                SaveLivesToPersistence();
            }
        }

        /// <summary>
        /// 移除直播
        /// </summary>
        /// <param name="guid">直播GUID</param>
        public static void RemoveLive(string guid)
        {
            var live = lives.FirstOrDefault(l => l.Guid == guid);
            if (live != null)
            {
                lives.Remove(live);
                LiveRemoved?.Invoke(null, new LiveEventArgs(live));
                AddLog($"移除直播: {live.Name}");
                SaveLivesToPersistence();
            }
        }

        /// <summary>
        /// 更新直播信息
        /// </summary>
        /// <param name="updatedLive">更新的直播信息</param>
        public static void UpdateLive(LiveInfo updatedLive, bool addLog = true)
        {
            if (updatedLive == null) return;

            var existingLive = lives.FirstOrDefault(l => l.Guid == updatedLive.Guid);
            if (existingLive != null)
            {
                var index = lives.IndexOf(existingLive);
                lives[index] = updatedLive;
                LiveUpdated?.Invoke(null, new LiveEventArgs(updatedLive));
                if (addLog)
                {
                    AddLog($"更新直播: {updatedLive.Name}");
                }
                SaveLivesToPersistence();
            }
        }

        /// <summary>
        /// 清空所有直播
        /// </summary>
        public static void ClearLives()
        {
            var count = lives.Count;
            lives.Clear();
            LivesCleared?.Invoke(null, EventArgs.Empty);
            AddLog($"清空直播列表，共移除 {count} 个直播");
            SaveLivesToPersistence();
        }

        /// <summary>
        /// 获取所有直播
        /// </summary>
        /// <returns>直播列表</returns>
        public static List<LiveInfo> GetAllLives()
        {
            return new List<LiveInfo>(lives);
        }

        /// <summary>
        /// 根据GUID获取直播
        /// </summary>
        /// <param name="guid">直播GUID</param>
        /// <returns>直播信息</returns>
        public static LiveInfo GetLiveByGuid(string guid)
        {
            return lives.FirstOrDefault(l => l.Guid == guid);
        }

        /// <summary>
        /// 根据状态获取直播列表
        /// </summary>
        /// <param name="status">直播状态</param>
        /// <returns>直播列表</returns>
        public static List<LiveInfo> GetLivesByStatus(bool status)
        {
            return lives.Where(l => l.Status == status).ToList();
        }

        // 直播事件参数类
        public class LiveEventArgs : EventArgs
        {
            public LiveInfo Live { get; }

            public LiveEventArgs(LiveInfo live)
            {
                Live = live;
            }
        }
    }
}